package com.party.admin.web.controller.crowdfund;

import com.party.admin.biz.activity.ActivityBizService;
import com.party.admin.biz.crowdfund.ProjectBizService;
import com.party.admin.biz.crowdfund.ProjectTransferBizService;
import com.party.admin.biz.crowdfund.SupportBizService;
import com.party.admin.biz.file.ExcelExportService;
import com.party.admin.biz.system.MemberBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.utils.excel.ExportExcel;
import com.party.admin.web.annotation.UserOperate;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.output.crowdfund.ProjectForActivityOutput;
import com.party.admin.web.dto.output.crowdfund.SupportCountOutput;
import com.party.common.paging.Page;
import com.party.core.exception.BusinessException;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.*;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.member.Member;
import com.party.core.model.wechat.WechatMerchants;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.crowdfund.ISupportTransferService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.wechat.IWechatMerchantsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by wei.li
 *
 * @date 2017/3/28 0028
 * @time 16:13
 */

@SuppressWarnings("all")
@Controller
@RequestMapping(value = "crowdfund/support")
public class SupportController {

    @Autowired
    private SupportBizService supportBizService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private ActivityBizService activityBizService;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IDistributorRelationService distributorRelationService;

    @Autowired
    private ExcelExportService excelExportService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IWechatMerchantsService wechatMerchantsService;

    @Autowired
    private ISupportTransferService supportTransferService;

    @Autowired
    private ProjectTransferBizService projectTransferBizService;

    @Autowired
    private MemberBizService memberBizService;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 根据分销关系编号查询支持列表
     * @param id 活动编号
     * @param relationId 分销关系
     * @param page 分页参数
     * @return
     */
    @RequestMapping(value = "listForDistributorId")
    public ModelAndView listForDistributorId(String id, String relationId, String merchantId, Page page){
        ModelAndView modelAndView = new ModelAndView("activity/supportList");
        modelAndView.addObject("isMultiple", false);
        modelAndView.addAllObjects(supportBizService.listForDistributorCommonActivity(id, relationId, merchantId, page));
        return modelAndView;
    }


    /**
     * 根据分销关系编号查询支持列表导出
     * @param relationId 分销关系
     * @param name 联合发起名称
     * @param response 响应参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "listForDistributorIdExport")
    public AjaxResult listForDistributorIdExport(String relationId, String name, String merchantId, HttpServletResponse response){
        String fileName = name + "联合发起的支持人" + ".xlsx";
        List<SupportWithMember> supportWithMemberList = supportBizService.listForDistributorId(relationId, merchantId, null);
        try {
            ExportExcel exportExcel = new ExportExcel(name + "联合发起的支持人", SupportWithMember.class).setDataList(supportWithMemberList);
            String allPath = excelExportService.getExcelPath(fileName, "support", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出支持人异常", e);
        }
        return AjaxResult.error("导出异常");
    }

    /**
     * 根据分销关系编号查询支持列表
     * @param relationId 分销关系
     * @param page 分页参数
     * @return
     */
    @RequestMapping(value = "event/listForDistributorId")
    public ModelAndView listEventForDistributorId(String relationId, String eventId, String merchantId, Page page){
        ModelAndView modelAndView = new ModelAndView("crowdfund/supportList");
        modelAndView.addObject("isMultiple", false);
        modelAndView.addAllObjects(supportBizService.listForDistributorCommonEvent(eventId, relationId, merchantId, page));
        return modelAndView;
    }


    /**
     * 根据分销关系编号查询支持列表导出
     * @param relationId 分销关系
     * @param response 响应参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "event/listForDistributorIdExport")
    public AjaxResult listEventForDistributorIdExport(String relationId, String merchantId, HttpServletResponse response){
        DistributorRelation distributorRelation = distributorRelationService.get(relationId);
        Member author = memberService.get(distributorRelation.getDistributorId());
        String fileName = author.getRealname() + "联合发起的支持人.xlsx";
        List<SupportWithMember> supportWithMemberList = supportBizService.listForDistributorId(relationId, merchantId,null);
        try {
            ExportExcel exportExcel = new ExportExcel(fileName, SupportWithMember.class).setDataList(supportWithMemberList);
            String allPath = excelExportService.getExcelPath(fileName, "support/event", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出支持人异常", e);
        }
        return AjaxResult.error("导出异常");
    }



    /**
     * 众筹项目查询支持
     * @param id 活动编号
     * @param page 分页参数
     * @return 支持列表
     */
    @RequestMapping(value = "listForProjectId")
    public ModelAndView listForProjectId(String id, SupportWithMember supportWithMember, Page page, HttpServletRequest request, Integer source){
        ModelAndView modelAndView = new ModelAndView("activity/supportForProjectList");
        //是否可以退款
        boolean isCan = false ;
        try {
            isCan = projectService.isCanRefund(supportWithMember.getProjectId());
        }catch (Exception e){
            logger.error(e.getMessage());
        }

        modelAndView.addObject("isCan", isCan);
        modelAndView.addObject("isMultiple", false);
        modelAndView.addAllObjects(supportBizService.listForProjectCommonActivity(id, supportWithMember, page, source));
        return modelAndView;
    }



    /**
     * 众筹项目查询支持
     * @param id 活动编号
     * @param page 分页参数
     * @return 支持列表
     */
    @RequestMapping(value = "dpListForProjectId")
    public ModelAndView dpListForProjectId(String id, SupportWithMember supportWithMember, Page page, HttpServletRequest request){
        page.setLimit(20);
        String sessionId = request.getSession().getId();
        ModelAndView modelAndView = new ModelAndView("activity/supportForDpProjectList");
        Activity activity = activityService.get(id);

        //众筹金额
        float actualAmount = activityBizService.actualAmountForTargetId(id);
        List<SupportWithMember> supportWithMemberList = supportService.listWithMemberAndMerchant(supportWithMember, page);

        ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
        projectWithAuthor.setTargetId(id);
        projectWithAuthor.setPayType(1);//直接众筹
        List<ProjectForActivityOutput> dpProjectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, null, activity.getMember());
        projectWithAuthor.setPayType(0);
        List<ProjectForActivityOutput> projectForActivityOutputList = projectBizService.projectForActivityList(projectWithAuthor, null, activity.getMember());
        Project project = projectService.get(supportWithMember.getProjectId());
        Member author = memberService.get(project.getAuthorId());

        modelAndView.addObject("actualAmount", actualAmount);
        modelAndView.addObject("activity", activity);
        modelAndView.addObject("projectId", supportWithMember.getProjectId());
        modelAndView.addObject("supportWithMember", supportWithMember);
        modelAndView.addObject("page", page);
        modelAndView.addObject("id", id);
        modelAndView.addObject("list", supportWithMemberList);
        modelAndView.addObject("name", author.getRealname());
        modelAndView.addObject("crowdfundNum", projectForActivityOutputList.size());
        modelAndView.addObject("directPayNum", dpProjectForActivityOutputList.size());
        // 获取转入的人
        Integer transferNum = supportTransferService.getShiftToPeopleTotal(activity.getId());

        modelAndView.addObject("transferNum", transferNum == null ? 0 : transferNum);
        modelAndView.addObject("merchantId", supportWithMember.getMerchantId());
        List<WechatMerchants> wechatMerchants = wechatMerchantsService.getMerchant(activity.getMember());
        modelAndView.addObject("wechatMerchants", wechatMerchants);
        return modelAndView;
    }

    /**
     * 导出众筹项目的支持
     * @param projectId 项目编号
     * @param name 项目名称
     * @param response 响应参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "listForProjectIdExport")
    public AjaxResult listForProjectIdExport(SupportWithMember supportWithMember, String name, HttpServletResponse response) {
        String fileName = name + "的众筹的支持人.xlsx";
        List<SupportWithMember> supportWithMemberList = supportService.listWithMemberAndMerchant(supportWithMember, null);
        String memberId = RealmUtils.getCurrentUser().getId();
        for (SupportWithMember swm : supportWithMemberList) {
            //替换手机号
            String phone = memberBizService.replacePhone(memberId, swm.getFavorerMobile());
            swm.setFavorerMobile(phone);
        }
        try {
            ExportExcel exportExcel = new ExportExcel(fileName, SupportWithMember.class).setDataList(supportWithMemberList);
            String allPath = excelExportService.getExcelPath(fileName, "support", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出支持人异常", e);
        }
        return AjaxResult.error("导出异常");
    }


    /**
     * 众筹项目查询支持
     * @param id 活动编号
     * @param page 分页参数
     * @return 支持列表
     */
    @RequestMapping(value = "listForRepresent")
    public ModelAndView listForRepresent(String id, SupportWithMember supportWithMember, Page page){
        ModelAndView modelAndView = new ModelAndView("activity/supportForRepresentList");

        //是否可以退款
        boolean isCan = false ;
        try {
            isCan = projectService.isCanRefund(supportWithMember.getProjectId());
        }catch (Exception e){
            logger.error(e.getMessage());
        }

        modelAndView.addObject("isMultiple", false);
        modelAndView.addObject("isCan", isCan);
        modelAndView.addAllObjects(supportBizService.listForRepresentCommonActivity(id, page, supportWithMember));
        return modelAndView;
    }

    /**
     * 导出众筹项目的支持
     * @param projectId 项目编号
     * @param name 项目名称
     * @param response 响应参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "listForRepresentExport")
    public AjaxResult listForRepresentExport(String projectId, String name, String merchantId, HttpServletResponse response){
        String fileName = name + "的众筹的支持人.xlsx";
        List<SupportWithMember> supportWithMemberList = supportBizService.listForProjectId(projectId, null, merchantId,null);
        try {
            ExportExcel exportExcel = new ExportExcel(fileName, SupportWithMember.class).setDataList(supportWithMemberList);
            String allPath = excelExportService.getExcelPath(fileName, "support", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出支持人异常", e);
        }
        return AjaxResult.error("导出异常");
    }


    @RequestMapping(value = "event/listForProjectId")
    public ModelAndView listEventForProjectId(String projectId, String eventId, String merchantId, String startTime, Page page){
        ModelAndView modelAndView = new ModelAndView("crowdfund/supportForProjectList");
        SupportWithMember supportWithMember = new SupportWithMember();
        supportWithMember.setMerchantId(merchantId);
        supportWithMember.setProjectId(projectId);
        modelAndView.addObject("isMultiple", false);
        modelAndView.addAllObjects(supportBizService.listForProjectCommonEvent(page, eventId, supportWithMember, startTime));
        return modelAndView;
    }

    @RequestMapping(value = "event/dpListForProjectId")
    public ModelAndView dpListForProjectId(String projectId, String eventId, String merchantId, String startTime, Page page){
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("crowdfund/supportForDpProjectList");
        List<SupportWithMember> supportWithMemberList = supportBizService.listForProjectId(projectId, startTime, merchantId, page);

        Integer representNum = distributorRelationService.countForEvent(eventId);
        Integer projectNum = projectService.countForEvent(eventId);
        Integer dpProjectNum = projectService.dpCountForEvent(eventId,null);

        Project project = projectService.get(projectId);
        Member author = memberService.get(project.getAuthorId());

        modelAndView.addObject("representNum", representNum);
        modelAndView.addObject("projectNum", projectNum);
        modelAndView.addObject("dpProjectNum", dpProjectNum);
        modelAndView.addObject("projectId", projectId);
        modelAndView.addObject("eventId", eventId);
        modelAndView.addObject("page", page);
        modelAndView.addObject("list", supportWithMemberList);
        modelAndView.addObject("name", author.getRealname());
        modelAndView.addObject("startTime", startTime);
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
        modelAndView.addObject("crowdfundEvent", crowdfundEvent);
        modelAndView.addObject("merchantId", merchantId);
        List<WechatMerchants> wechatMerchants = wechatMerchantsService.getMerchant(crowdfundEvent.getCreateBy());
        modelAndView.addObject("wechatMerchants", wechatMerchants);
        return modelAndView;
    }

    /**
     * 导出众筹项目的支持
     * @param projectId 项目编号
     * @param response 响应参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "event/listForProjectIdExport")
    public AjaxResult listEventForProjectIdExport(String projectId, String merchantId, HttpServletResponse response){
        Project project = projectService.get(projectId);
        Member author = memberService.get(project.getAuthorId());
        String fileName = author.getRealname() + "的众筹的支持人.xlsx";
        List<SupportWithMember> supportWithMemberList = supportBizService.listForProjectId(projectId, null, merchantId,null);
        try {
            ExportExcel exportExcel = new ExportExcel(fileName, SupportWithMember.class).setDataList(supportWithMemberList);
            String allPath = excelExportService.getExcelPath(fileName, "support/event", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出支持人异常", e);
        }
        return AjaxResult.error("导出异常");
    }


    /**
     * 众筹项目查询支持
     * @param projectId 众筹编号
     * @param page 分页参数
     * @return 支持列表
     */
    @RequestMapping(value = "event/listForRepresent")
    public ModelAndView listEventForRepresent( String projectId, String eventId, String merchantId, Page page){
        ModelAndView modelAndView = new ModelAndView("crowdfund/supportForRepresentList");
        SupportWithMember supportWithMember = new SupportWithMember();
        supportWithMember.setProjectId(projectId);
        supportWithMember.setMerchantId(merchantId);
        modelAndView.addAllObjects(supportBizService.listForRepresentCommonEvent(eventId, page, supportWithMember));
        modelAndView.addObject("isMultiple", false);
        return modelAndView;
    }

    /**
     * 导出众筹项目的支持
     * @param projectId 项目编号
     * @param response 响应参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "event/listForRepresentExport")
    public AjaxResult listEventForRepresentExport(String projectId, String merchantId, HttpServletResponse response){
        Project project = projectService.get(projectId);
        Member author = memberService.get(project.getAuthorId());
        String fileName = author.getRealname()+ "的众筹的支持人.xlsx";
        List<SupportWithMember> supportWithMemberList = supportBizService.listForProjectId(projectId, null, merchantId,null);
        try {
            ExportExcel exportExcel = new ExportExcel(fileName, SupportWithMember.class).setDataList(supportWithMemberList);
            String allPath = excelExportService.getExcelPath(fileName, "support/event", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出支持人异常", e);
        }
        return AjaxResult.error("导出异常");
    }


    /**
     * 支持退款
     * @param id 支持编号
     * @return 交互数据
     */
    @ResponseBody
    @UserOperate(moduleName = "众筹项目-数据查看-众筹的列表-单个退款", behaviorType = BehaviorType.REFUND)
    @RequestMapping(value = "refund")
    public AjaxResult refund(String id){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            Support support = supportService.get(id);
            boolean canRefund = projectService.isCanRefund(support.getProjectId());
            if(!canRefund){
                ajaxResult.setDescription("该众筹者已众筹成功，暂不支持退款");
                return ajaxResult;
            }

            supportBizService.sendRefund(id);
        } catch (BusinessException e) {
            ajaxResult.setDescription(e.getMessage());
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 统计图表
     * @param projectId 项目编号
     * @return 输出视图
     */
    @ResponseBody
    @RequestMapping(value = "chart")
    public AjaxResult chart(String projectId){
        AjaxResult ajaxResult = new AjaxResult();
        SupportCountOutput supportCountOutput = supportBizService.chart(projectId);
        ajaxResult.setSuccess(true);
        ajaxResult.setData(supportCountOutput);
        return ajaxResult;
    }

    /**
     * 统计图表视图
     * @param projectId 项目编号
     * @return 输出视图
     */
    @RequestMapping(value = "chartView")
    public ModelAndView chartView(String projectId, String targetId){
        ModelAndView modelAndView = new ModelAndView("crowdfund/supportChart");
        modelAndView.addObject("projectId", projectId);
        modelAndView.addObject("targetId", targetId);
        return modelAndView;
    }

    /**
     * 统计图表视图
     * @param projectId 项目编号
     * @return 输出视图
     */
    @RequestMapping(value = "supporterTransferDataRepair")
    public AjaxResult supporterTransferDataRepair(HttpServletRequest request){
        AjaxResult ajaxResult = new AjaxResult();
        projectTransferBizService.supporterTransferDataRepair();
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

}
